<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { axioswmedical } from '../../http/axiosWrtie';
import { showToast } from 'vant';

const router = useRouter();
const route = useRoute();

const refundReason = ref('');
const refundLoading = ref(false);

// 使用ref初始化这些值，以便在onMounted中更新
const itemName = ref('');
const amount = ref(0);
const orderNo = ref('');

// 在组件挂载后获取路由参数
onMounted(() => {
  // 获取路由参数并设置默认值
  itemName.value = route.query.itemName ? String(route.query.itemName) : '';
  amount.value = route.query.amount ? Number(route.query.amount) : 0;
  orderNo.value = route.query.orderNo ? String(route.query.orderNo) : '';
  
  // 如果缺少必要参数，提示错误
  if (!orderNo.value || !amount.value) {
    showToast('缺少必要的订单信息');
  }
  showToast(itemName.value+","+amount.value+","+orderNo.value)
});

const handleRefund = () => {
  if (!refundReason.value) {
    showToast('请填写退款原因');
    return;
  }
  refundLoading.value = true;
  try {
    const refundParams = {
      outTradeNo: orderNo.value,
      refundAmount: amount.value.toFixed(2),
      refundReason: refundReason.value
    };
    
     axioswmedical.post('/Alipay/Refund', refundParams).then(response=>{
      if (response.data.code === 200) {
        showToast(response.data.msg);
        router.replace('/refund'); // 假设退款列表页路径为 /refund
      } else {
        showToast(`退款失败: ${response.data.msg || '未知错误'}`);
      }
    })
    
  } catch  {
    showToast('退款请求失败，请稍后再试');
  } finally {
    refundLoading.value = false;
  }
};

const backToList = () => {
  router.back();
};
</script>

<template>
  <div class="refund-form-page">
    <div class="header">
      <van-nav-bar
        title="申请退款"
        left-arrow
        @click-left="backToList"
      />
    </div>
    <div class="content">
      <div class="refund-item-info">
        <div>项目：{{ itemName }}</div>
        <div>金额：¥{{ amount.toFixed(2) }}</div>
      </div>
      <van-field
        v-model="refundReason"
        label="退款原因"
        placeholder="请输入退款原因"
        type="textarea"
        rows="3"
      />
      <div class="action-buttons">
        <van-button
          type="danger"
          block
          :loading="refundLoading"
          loading-text="处理中..."
          @click="handleRefund"
        >
          确认退款
        </van-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.refund-form-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}
.content {
  flex: 1;
  padding: 16px;
}
.refund-item-info {
  margin-bottom: 16px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.action-buttons {
  margin-top: 24px;
}
</style> 